<template>
  <div class="flex h-full">
    <a-card class="mr-2 w-[400px]" :body-style="{ height: '100%', display: 'flex', flexDirection: 'column', padding: '8px' }">
      <SelectTree ref="suitTreeRef" class="flex-1" :emr-loading="emrLoading" have-add @select="getTemplateXml" @refresh="getTemplateXml()" />
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <a-card
        class="flex-1 overflow-auto"
        :body-style="{ padding: '8px', height: '100%', overflow: 'hidden', display: 'flex', flexDirection: 'column', position: 'relative' }"
      >
        <div class="flex pr-8">
          <a-space>
            <!-- state.ctl.DCExecuteCommand('FileOpen') -->
            <a-upload name="file" :custom-request="beforeUpload" :show-upload-list="false">
              <a-button ref="doctorAdviceRef" type="primary" :disabled="!store.templateId || store.templateInfo.templateStatus === '1'">
                导入病历模版
              </a-button>
            </a-upload>
            <a-button class="ml-2" :disabled="!store.templateId || store.templateInfo.templateStatus === '1'" @click="onClickSave()"> 保存 </a-button>
            <a-button v-if="store.templateInfo.templateStatus === '1'" :disabled="!store.templateId" @click="onClickMedical('0')"> 撤销 </a-button>
            <a-button v-else :disabled="!store.templateId" @click="onClickMedical('1')"> 发布 </a-button>
          </a-space>
        </div>
        <a-tabs v-model:active-key="activeKey">
          <a-tab-pane key="1" tab="编辑">
            <EditModule :disabled="store.templateInfo.templateStatus === '1'" @change-font-style="changeFontStyle" @change-font-sub-sup="onChangeFontSubSup" />
          </a-tab-pane>
          <a-tab-pane key="2" tab="插入" :disabled="!store.templateId"><InsertModule :ctl="state.ctl" /></a-tab-pane>
        </a-tabs>
        <a-spin :spinning="emrLoading" tip="初始化中..." wrapper-class-name="flex-1 mt-2 overflow-hidden">
          <div class="flex justify-center h-full overflow-hidden">
            <div class="relative w-[820px] mx-auto" :class="store.templateInfo.templateStatus === '1' ? 'template-status' : ''">
              <div
                v-show="isShowEMR"
                id="myWriterControl"
                dctype="WriterControlForWASM"
                contentrendermode="NormalHtmlEditable"
                workspacebackcolorstring="#DEDEDE"
                useclassattribute="true"
                heightcompress="true"
                backgroundtextoutputmode="None"
                imagedataembedinhtml="true"
                HeaderFooterEditable="true"
                pixelpagespacing="5"
                clientcontextmenutype="Custom"
                usedcwriterminijs="True"
                showdebuginfo="false"
                registercodeindex="0"
              >
                正在加载...
              </div>
              <a-empty v-show="!isShowEMR" :description="emptyStr" />
            </div>
          </div>
        </a-spin>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import axios from 'axios'
import useStore from './store.js'
import SelectTree from './components/SelectTree.vue'
import EditModule from './components/EditModule.vue'
import InsertModule from './components/InsertModule.vue'

const store = useStore()
const activeKey = ref('1')
const emptyStr = ref('请选择模板')
const suitTreeRef = ref()
const doctorAdviceRef = ref(null)
const isShowEMR = ref(false)
const emrLoading = ref(true)
// 发布和撤销
const onClickMedical = async (status) => {
  const { code } = await post('emr/emrTemplate/doChangeEmrTempleteStatus/' + store.templateId + '/' + status)
  if (code !== 0) return message.error('失败')
  message.success('成功')
  store.templateInfo.templateStatus = status
  suitTreeRef.value.getData()
  addStatusDom()
}

const state = reactive({ ctl: null })
// 上传
const beforeUpload = async (options) => {
  const { file } = options
  const isJpgOrPng = file.type === 'text/xml'
  if (!isJpgOrPng) {
    message.error('请上传xml格式!')
    return
  }
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!isLt2M) {
    message.error('上传文件最大10MB!')
    return
  }
  const formData = new FormData()
  formData.append('file', file)
  // await axios.post('/api/v1/emr/file/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  const res = await axios.post('/api/v1/emr/file/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
  getDoSaveTemplate(res.data.msg)
}

// const getFile = async (fileName) => {
//   const { code, data, msg } = await get('emr/file/getUrl?fileName=' + fileName)
//   if (code !== 0) return message.error(msg || '操作失败')
//   getDoSaveTemplate(data)
// }

//  上传保存模版
const getDoSaveTemplate = async (fileName) => {
  const { code, msg } = await post('emr/emrTemplate/doSaveEmrTemplete', { templateContentUrl: fileName, id: store.templateId, templateType: 2 })
  if (code !== 0) return message.error(msg)
  message.success('上传成功')
  getTemplateXml()
}
//  保存模版
const onClickSave = async () => {
  const { code, msg } = await post('/emr/emrTemplate/doUpdateEmrTemplete', { templateXmlContent: state.ctl.XMLTextForSave, id: store.templateId })
  if (code !== 0) return message.error(msg)
  message.success('保存成功')
  getTemplateXml()
}

// 电子病历
const loadScript = () => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://www.dcwriter.cn:8099/ServicePage.aspx?wasmres=dcwriter5.js'
    script.onload = () => resolve()
    document.head.insertBefore(script, null)
  })
}
const getFontObject = ref()

// 根据模版id获取模版
const getTemplateXml = async () => {
  isShowEMR.value = false
  emptyStr.value = '请选择模板'
  if (store.templateId) {
    const ctl = document.getElementById('myWriterControl')
    const { data, code, msg } = await post('/emr/emrTemplate/getEmrTempleteDocument?templateId=' + store.templateId)
    if (code !== 0) return message.error(msg)
    isShowEMR.value = true
    if (!data) {
      isShowEMR.value = false
      emptyStr.value = '请上传模板'
      return
    }
    try {
      ctl.LoadDocumentFromString(data)
    } catch (error) {
      console.error('🏳️‍🌈 <输出> 解析xml错误:', error)
    }

    getFontObject.value = ctl.getFontObject()
    state.ctl = ctl
    addStatusDom()
  }
}
const addStatusDom = () => {
  const dom = document.querySelector('.template-status div[dctype="page-container"]')
  //添加角标
  const span = document.createElement('span')
  span.style.position = 'absolute'
  span.style.width = '36px'
  span.style.height = '36px'
  span.style.top = '5px'
  span.style.right = '9px'
  span.style.backgroundImage =
    'url()'
  dom.appendChild(span)
}
const changeFontStyle = (e) => {
  if (state.ctl) state.ctl.setFontObject(e)
}
const onChangeFontSubSup = (e) => {
  if (state.ctl) state.ctl.DCExecuteCommand(e.name, e.val, e.memo)
}
onMounted(async () => {
  await loadScript()
  const ctl = document.getElementById('myWriterControl')
  if (window.CreateWriterControlForWASM) {
    window.CreateWriterControlForWASM(ctl)
  }
  window.WriterControl_OnLoad = () => {
    emrLoading.value = false
  }
  // emrLoading.value = false
  // getTemplateXml()
})
// function onWriteData() {
//   const values = {
//     zyh: '1001',
//     EMR_name: '李小四',
//     sex: '女',
//     room: 'A301',
//     tel: '18333333332',
//     cwh: '05',
//     ksmc: '综合内科',
//     age: '23',
//     indate: '2019-3-27',
//     tongue_coated: '黄厚',
//     tongue_quality: '淡红',
//     direction: '1,2,3',
//     EMR_mar: '未婚',
//     minzu: '汉族'
//   }
//   state.ctl.SetDocumentParameterValue('emrinfo', values)
//   state.ctl.WriteDataFromDataSourceToDocument()
// }
</script>
<style lang="less" scoped>
:deep(.ant-spin-container) {
  height: 100%;
}
</style>
